<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/7/22
 * Time: 23:05
 */

namespace zch\firstLaravel\container;

class Container
{
    protected $bind = []; //容器（类的盒子）

    protected static $instance; //用于指定当前的实例

    protected $instances; //保存容器解析出来的实例做到共享，避免重复创建

    /**
     * 容器的绑定操作
     * @param $abstract
     * @param $object
     */
    public function bind($abstract, $object)
    {
        $this->bind[$abstract] = $object;
    }

    /**
     * 检测实例是否存在容器中
     * @param $abstract
     * @return bool
     */
    public function has($abstract)
    {
        return isset($this->bind[$abstract]);
    }

    /**
     * 将实例作为共享
     * @param $abstract
     * @param $instance
     */
    public function instance($abstract, $instance)
    {
        if(isset($this->bind[$abstract])){
            unset($this->bind[$abstract]);
        }
       $this->instances[$abstract] = $instance;
    }

    /**
     * 单例模式获取当前实例
     * @return mixed
     */
    public static function getInstace()
    {
        if(is_null(static::$instance)){
            static::$instance = new static;
        }
        return static::$instance;
    }


    public function make($abstract, $parameters = [])
    {
         if(isset($this->instances[$abstract])){
             return $this->instances[$abstract];
         }

         if(isset($this->bind[$abstract])){
             $class = $this->bind[$abstract];
             $object = (empty($parameters)) ? new $class() :new $class(...$parameters);
             return $this->instances[$abstract] = $object;
         }

         throw new \Exception('没有找到对应的实例'.$abstract, 1);
    }

}